// 读者端脚本：注册/登录、检索、借阅、查看个人借阅记录
document.addEventListener('DOMContentLoaded', () => {
  restoreSession();
  loadBooks();
  loadBorrowBookOptions();
  loadMyBorrowRecords();

  document.getElementById('registerForm').addEventListener('submit', onRegisterSubmit);
  document.getElementById('logoutBtn').addEventListener('click', logout);
  document.getElementById('searchBtn').addEventListener('click', searchBooks);
  document.getElementById('clearSearchBtn').addEventListener('click', () => { document.getElementById('searchQuery').value=''; loadBooks(); });
  document.getElementById('borrowForm').addEventListener('submit', onBorrowSubmit);
});

const SESSION_KEY = 'lm_current_user';

function saveSession(user) {
  localStorage.setItem(SESSION_KEY, JSON.stringify(user));
  updateUI();
}

function restoreSession() { updateUI(); }

function logout() { localStorage.removeItem(SESSION_KEY); updateUI(); }

function updateUI() {
  const cur = localStorage.getItem(SESSION_KEY);
  const el = document.getElementById('currentUser');
  if (cur) {
    const u = JSON.parse(cur);
    el.textContent = `${u.name} (id:${u.id})`;
  } else {
    el.textContent = '未登录';
  }
}

async function onRegisterSubmit(e) {
  e.preventDefault();
  const name = document.getElementById('regName').value;
  const email = document.getElementById('regEmail').value;
  const password = document.getElementById('regPassword').value;
  try {
    const res = await fetch('/api/users/register', {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({name, email, password})
    });
    if (!res.ok) { const err = await res.json(); return alert('注册失败: '+(err.error||res.statusText)); }
    const user = await res.json();
    saveSession(user);
    alert('注册并登录成功');
    document.getElementById('registerForm').reset();
    await loadBorrowBookOptions();
    await loadMyBorrowRecords();
  } catch (e) { alert('网络错误'); }
}

async function loadBooks() {
  try {
    const q = document.getElementById('searchQuery').value.trim();
    const url = q ? `/api/books/search?q=${encodeURIComponent(q)}` : '/api/books';
    const res = await fetch(url);
    const books = await res.json();
    const tb = document.getElementById('bookList');
    tb.innerHTML = '';
    books.forEach(b => {
      const tr = document.createElement('tr');
      tr.innerHTML = `<td>${esc(b.title)}</td><td>${esc(b.author)}</td><td>${esc(b.isbn)}</td><td>${b.available?'是':'否'}</td>
        <td>${b.available?'<span>可借</span>':'<span>不可借</span>'}</td>`;
      tb.appendChild(tr);
    });
  } catch (e) { console.warn(e); }
}

async function searchBooks(e) {
  await loadBooks();
}

async function loadBorrowBookOptions() {
  const sel = document.getElementById('borrowBook');
  sel.innerHTML = '';
  try {
    const res = await fetch('/api/books');
    const books = await res.json();
    books.forEach(b => {
      const opt = document.createElement('option');
      opt.value = b.id;
      opt.textContent = `${b.title} ${b.available? '(可借)':'(不可借)'}`;
      sel.appendChild(opt);
    });
  } catch (e) { console.warn(e); }
}

async function onBorrowSubmit(e) {
  e.preventDefault();
  const cur = localStorage.getItem(SESSION_KEY);
  if (!cur) return alert('请先注册/登录');
  const user = JSON.parse(cur);
  const bookId = Number(document.getElementById('borrowBook').value);
  const days = Number(document.getElementById('borrowDays').value) || 14;
  try {
    const res = await fetch('/api/borrow', {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({user_id: user.id, book_id: bookId, days})
    });
    if (!res.ok) { const err = await res.json(); return alert('借阅失败: '+(err.error||res.statusText)); }
    alert('借书成功');
    await loadBooks();
    await loadBorrowBookOptions();
    await loadMyBorrowRecords();
  } catch (e) { alert('网络错误'); }
}

async function loadMyBorrowRecords() {
  const cur = localStorage.getItem(SESSION_KEY);
  const tbody = document.getElementById('borrowList');
  tbody.innerHTML = '';
  if (!cur) return;
  const user = JSON.parse(cur);
  try {
    const res = await fetch(`/api/borrow_records?user_id=${user.id}`);
    const records = await res.json();
    const booksRes = await fetch('/api/books');
    const books = await booksRes.json();
    const bookMap = {};
    books.forEach(b => bookMap[b.id]=b);
    records.forEach(rec => {
      const tr = document.createElement('tr');
      tr.innerHTML = `<td>${rec.id}</td>
        <td>${esc((bookMap[rec.book_id]||{}).title||'')}</td>
        <td>${fmt(rec.borrowed_at)}</td>
        <td>${fmt(rec.due_at)}</td>
        <td>${rec.returned?fmt(rec.returned_at):'否'}</td>
        <td>${rec.returned?'':'<button data-id="'+rec.id+'" class="return-btn">归还</button>'}</td>`;
      tbody.appendChild(tr);
    });
    tbody.querySelectorAll('.return-btn').forEach(btn => btn.addEventListener('click', onReturnClick));
  } catch (e) { console.warn(e); }
}

async function onReturnClick(e) {
  const id = e.currentTarget.dataset.id;
  if (!confirm('确认归还？')) return;
  try {
    const res = await fetch(`/api/return/${id}`, { method: 'POST' });
    if (!res.ok) { const err = await res.json(); return alert('归还失败: '+(err.error||res.statusText)); }
    const data = await res.json();
    alert('已归还，罚款: ' + (data.fine || 0));
    await loadBooks();
    await loadMyBorrowRecords();
  } catch (e) { alert('网络错误'); }
}

function esc(s){ if (!s) return ''; return String(s).replace(/[&<>"']/g, m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m])); }
function fmt(v){ if (!v) return ''; try { const d=new Date(v); return isNaN(d)?v:d.toLocaleString(); } catch(e){ return v; } }